// 导入数据库操作模块
const db = require('../db/index')
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');


//上传产品图片
exports.uploadProductImage = (req, res) => {
    const created_at = new Date()
    if (!req.files || !req.files[0]) {
        return res.status(400).send('No image uploaded');
    }
    const uploadedImage = req.files[0];
    const productId = req.body.product_id;
    // 获取上传文件的原始文件名
    const fileName = uploadedImage.originalname;
    // 构造图片 URL
    const imageUrl = `http://127.0.0.1:3300/public/upload/${fileName}`;

    // 将图片信息存储到数据库中，与产品ID关联
    const sql = 'update product_image SET ? where product_id = ?';
    db.query(sql, [{
        image_url: imageUrl,
        created_at: created_at,
    }, productId], (err, results) => {
        if (err) {
            return res.status(500).send(err);
        }
        // 返回上传成功的响应
        res.json({
            status: 0,
            message: '修改成功'
        });
    });
};
//获取imgurl 列表
exports.getProductImageList = (req, res) => {
    const sql = `SELECT img.image_url,mapping.product_id,mapping.product_name FROM product_image img
     RIGHT JOIN  productnamemapping mapping  on img.product_id = mapping.product_id`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}


//根据分类获取产品列表
exports.getProductListByType = (req, res) => {
    const sql = `SELECT product_name,image_url,pimg.product_id FROM  product pro LEFT JOIN product_image pimg on pro.product_id = pimg.product_id
     WHERE pro.product_category = ?`
    db.query(sql, req.body.data, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}

//获取产品分类
exports.getProductCategory = (req, res) => {
    const sql = 'select set_value from setting where id = 13'
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })

}


//根据产品id获取产品详情
exports.getProductDetailByProductId = (req, res) => {
    const querysql = `select mp.id,
    mp.product_id,
    mp.product_name,
    mp.product_point,
    mp.product_function ,pro.product_in_warehouse_number,pro.product_single_price,image_url
    FROM productnamemapping mp LEFT JOIN product pro on mp.product_id = pro.product_id
    left join product_image img on mp.product_id = img.product_id WHERE mp.product_id = ?`
    db.query(querysql, req.body.data, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}
